class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def findTilt(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        self.total = 0

        def search(node):
            left_v = 0
            right_v = 0
            if node.left:
                left_v = search(node.left)
            if node.right:
                right_v = search(node.right)
            self.total += abs(left_v - right_v)
            return left_v + right_v + node.val

        search(root)

        return self.total
